package com.xltt.vehicleControl.activity;

import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.xltt.vehicleControl.BuildConfig;
import com.xltt.vehicleControl.R;
import com.xltt.vehicleControl.base.BaseMvpActivity;
import com.xltt.vehicleControl.base.MyApplication;
import com.xltt.vehicleControl.bean.BaseData;
import com.xltt.vehicleControl.bean.BaseResult;
import com.xltt.vehicleControl.bean.ReposFactory;
import com.xltt.vehicleControl.bean.UserResponse;
import com.xltt.vehicleControl.contants.Constants;
import com.xltt.vehicleControl.contants.ResponseCode;
import com.xltt.vehicleControl.contract.IUserContract;
import com.xltt.vehicleControl.manager.InputTextManager;
import com.xltt.vehicleControl.presenter.UserPresenter;
import com.xltt.vehicleControl.util.ActivityManager;
import com.xltt.vehicleControl.util.Logger;
import com.xltt.vehicleControl.util.Md5Util;
import com.xltt.vehicleControl.util.NetWorkUtils;
import com.xltt.vehicleControl.util.SharedPreferencesUtils;
import com.xltt.vehicleControl.util.ToastUtil;
import com.xltt.vehicleControl.view.ClearEditText;
import com.xltt.vehicleControl.view.PasswordEditText;
import com.xltt.vehicleControl.view.SubmitButton;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


public class LoginActivity extends BaseMvpActivity<LoginActivity, UserPresenter> implements IUserContract.IUserView {

    @BindView(R.id.country_format)
    TextView mUserFormatView;
    @BindView(R.id.user)
    ClearEditText mUserView;
    @BindView(R.id.password)
    PasswordEditText mPasswordView;
    @BindView(R.id.login_btn)
    SubmitButton mLoginView;

    public static final String BLE_REQUETS_USERNAME = "ble_username";
    public static final String BLE_REQUETS_PASSWORD = "ble_password";

    public static final int BLE_LOGIN = 0;
    public static final int NONE_LOGIN = 1;
    public static final String REQUETS_USERNAME_FORMAT = "username_format";
    public static final String REQUETS_USERNAME = "username";
    public static final String REQUETS_PASSWORD = "password";
    public static final String TOKEN = "token";
    public static final String DEVICE_ID = "deviceId";
    public static final String USERID = "userId";
    public static final String CLIENT_ID = "clientId";
    public static final int LOGOUT_CODE = 1;//登出,需要清除密码

    @Override
    protected void initViews() {
        InputTextManager.with(this)
                .addView(mUserView)
                .addView(mPasswordView)
                .setMain(mLoginView)
                .build();
        initUserInfo();
    }

    /**
     * 初始化用户信息
     */
    private void initUserInfo(){
        String defaultUserFormat = getLoginUserFormat();
        String defaultUser = getLoginUser(BLE_LOGIN);
        String defaultPassword = getLoginPassword(BLE_LOGIN);
//        String defaultUser = "601831200601";
//        String defaultPassword = "5d93ceb70e2bf5daa84ec3d0cd2c731a";
        //1、获取绑定的账号格式
        boolean autoLogin = false;
        if(!TextUtils.isEmpty(defaultUser)){//蓝牙传输账号不为空，截取前面2位不要
            defaultUserFormat = defaultUser.substring(0,2);
            defaultUser = defaultUser.substring(2);
        }
        //2、判断是否第三方登录进行无密码绑定
        if(!TextUtils.isEmpty(defaultUser) && !TextUtils.isEmpty(defaultPassword)){
            autoLogin = true;
        }else if(!TextUtils.isEmpty(defaultUser) && TextUtils.isEmpty(defaultPassword)){
            Logger.d("app绑定无密码，开始填充账号EditText");
        } else {
            defaultUser = getLoginUser(NONE_LOGIN);
            defaultPassword = getLoginPassword(NONE_LOGIN);
        }
//        String defaultUser = getLoginUser();
//        String defaultPassword = getLoginPassword();
        mUserFormatView.setText(defaultUserFormat);
        mUserView.setText(defaultUser);
        mPasswordView.setText(defaultPassword);
        //3、自动登录
        if(autoLogin){
            mLoginView.performClick();
        }
        Logger.d("defaultUser = " + defaultUser + " , defaultPassword = " + defaultPassword + ",run debug mode = " + BuildConfig.DEBUG);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected UserPresenter createPresenter() {
        return UserPresenter.getInstance();
    }

    @Override
    public void loginResult(BaseResult<UserResponse> data) {
        int resultCode = data.getCode();
        //1.验证账号密码正确性
        if(resultCode == ResponseCode.CODE_4030){
            mLoginView.showError(3000);
            ToastUtil.show(this,getString(R.string.login_user_error_4030));
            return;
        }

        if(resultCode == ResponseCode.CODE_4002){
            mLoginView.showError(3000);
            ToastUtil.show(this,getString(R.string.login_password_error_4002));
            return;
        }
        if(resultCode == 1410){
            mLoginView.showError(3000);
            ToastUtil.show(this,getString(R.string.input_login_pwd_error));
            return;
        }
        if(resultCode == ResponseCode.CODE_6666){
            mLoginView.showError(3000);
            ToastUtil.show(this,getString(R.string.server_error));
            return;
        }
        UserResponse user = data.getData();
        String token = user.getAccessToken();
        String clientId = user.getClientId();
        Logger.d("token = " + token + " ,clientId = " + clientId + " ,resultCode = " + resultCode);
        if(TextUtils.isEmpty(token)){
            mLoginView.showError(3000);
            ToastUtil.show(this,getString(R.string.login_error));
            return;
        }
        //2.记录登录成功后需要保存的数据
        ReposFactory.getInstance().setUserResponse(user);
        mLoginView.showSucceed();
        //3.记录token和userId到文件，用来下次不需要登录获取数据使用
        SharedPreferencesUtils.setParam(this,TOKEN,token);
        SharedPreferencesUtils.setParam(this,USERID,user.getUserId());
        SharedPreferencesUtils.setParam(this,CLIENT_ID,user.getClientId());
        Logger.d("MyApplication save userId = " + user.getUserId() + ",client_id = " + user.getClientId() + ",token = " + token);
        //4.跳转到首页
        if(Constants.DEBUG){
            SharedPreferencesUtils.setParam(this,Constants.FIRST_BOOT,1);
        }else{
            Settings.Global.putInt(this.getContentResolver(), Constants.FIRST_BOOT,1);//记录已经登录过
        }

        startActivityForResult(new Intent(this,LauncherActivity.class),0);
        ActivityManager.getInstance().finishAllActivities(LauncherActivity.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode == LOGOUT_CODE){

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void logoutResult(BaseResult<BaseData> user) {

    }

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void onError(String result) {
        ToastUtil.show(this,getString(R.string.server_error));
        mLoginView.showError(3000);
    }

    @OnClick({R.id.login_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                login();
                break;
        }
    }


    /**
     * 用户登录
     */
    private void login(){
        String userNameFormat = mUserFormatView.getText().toString();
        String userName = mUserView.getText().toString();
        String password = mPasswordView.getText().toString();
        //1.判断阿里推送书否完成初始化
        MyApplication mMyApplication = ((MyApplication)getApplication());
        String deviceId = mMyApplication.getAliDeviceId();
        if(TextUtils.isEmpty(deviceId)){
            mLoginView.showError(3000);
            ToastUtil.show(this,getString(R.string.push_service_error));
            if(Md5Util.isMD5Password(password)){
                mPasswordView.setText("");
                cleanBluethUserInfo();
            }
            return;
        }
        //2.网络判断
        if(!NetWorkUtils.isAvailable(this)){
            mLoginView.showError(3000);
            ToastUtil.show(this,getString(R.string.please_connect_network_login_tip));
            if(Md5Util.isMD5Password(password)){
                mPasswordView.setText("");
                cleanBluethUserInfo();
            }
            return;
        }
        //3.非空判断
        if(TextUtils.isEmpty(userName)){
            ToastUtil.show(LoginActivity.this,getString(R.string.please_input_user_name));
            return;
        }
        if(TextUtils.isEmpty(password)){
            ToastUtil.show(LoginActivity.this,getString(R.string.please_input_user_pwd));
            return;
        }
        //4.隐藏软键盘
        hideKeyboard(getCurrentFocus());
        //5.保存账号密码
        setLoginUserFormat(userNameFormat);
        setLoginUser(userName);
        if(!Md5Util.isMD5Password(password)){
            setLoginPassword(password);
        }else{
            mPasswordView.setText("");
        }
        //6.清空ble账号密码，确保下次不在自动登录
        cleanBluethUserInfo();
        //7.调用接口登录
        Map<String, String> mLoginMap = new HashMap<>();
        mLoginMap.put(REQUETS_USERNAME,userNameFormat + userName);
        //String md5Password = Md5Util.encrypt(password);
        if(!Md5Util.isMD5Password(password)){
            password = Md5Util.encrypt(password);
        }
        mLoginMap.put(REQUETS_PASSWORD, password);
        getPresenter().loginByUserAndPassWord(mLoginMap);
        mLoginView.showProgress();

    }

    /**
     * 隐藏软键盘
     */
    public void hideKeyboard(View view) {
        if (view == null) {
            return;
        }
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (manager != null) {
            manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
